package models

import (
	"encoding/json"
	"gorm.io/gorm"
	"time"
)

type Article struct {
	ID uint `json:"id" gorm:"primary_key;auto_increment"`
	// 标题，内容
	Title        string         `json:"title" gorm:"size:255;not null"`
	Content      string         `json:"content" gorm:"size:255;not null"`
	CoverImage   string         `gorm:"size:255" json:"cover_image"`
	State        string         `gorm:"type:enum('draft','published','archived');default:'draft'" json:"state"`
	CommentCount int            `gorm:"default:0" json:"comment_count"`
	TOC          string         `gorm:"type:text" json:"toc"` // 存储TOC的JSON字符串
	PublishedAt  *time.Time     `json:"published_at"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	DeletedAt    gorm.DeletedAt `gorm:"index" json:"-"`
}

// 创建文章请求结构体
type CreateArticleRequest struct {
	Title      string `json:"title" binding:"required"`
	Content    string `json:"content" binding:"required"`
	CoverImage string `json:"cover_image"`
	State      string `json:"state"`
	TOC        string `json:"toc" binding:"required"`
	CategoryID *uint  `json:"category_id"`
}

// TOCItem 目录项
type TOCItem struct {
	Level  int    `json:"level"`  // 标题级别
	Title  string `json:"title"`  // 标题文本
	Anchor string `json:"anchor"` // 锚点ID
}

// Article 文章模型

// GetTOCItems 解析TOC JSON数据
func (a *Article) GetTOCItems() ([]TOCItem, error) {
	if a.TOC == "" {
		return []TOCItem{}, nil
	}
	var tocItems []TOCItem
	err := json.Unmarshal([]byte(a.TOC), &tocItems)
	return tocItems, err
}

// SetTOCItems 设置TOC数据
func (a *Article) SetTOCItems(tocItems []TOCItem) error {
	tocJSON, err := json.Marshal(tocItems)
	if err != nil {
		return err
	}
	a.TOC = string(tocJSON)
	return nil
}
